'''
Descripttion: 
Author: White
Date: 2025-01-09 12:16:57
LastEditTime: 2025-01-09 15:41:56
'''
'''
Descripttion: 
Author: White
Date: 2025-01-09 12:16:57
LastEditTime: 2025-01-09 15:32:33
'''
# import db
# from app import app
# from app.model.equipment_fault import Equipment_fault
# from db import db
# import uuid
from functools import wraps

from flask import render_template, request, flash, redirect, url_for, session
from flask_login import login_required, current_user, login_user, logout_user

from app import app, login_manager
from app.model import *
from flask import jsonify, request
from db import db
import uuid
from flask import render_template
from app.api import *


@login_manager.user_loader
def load_user(user_id):
    print(user_id)
    # 根据 user_id 从数据库中加载用户对象
    # 这里 user_id 是存储在用户会话中的唯一标识符
    # 返回值应该是一个 User 对象，或者如果用户不存在则返回 None
    return User.query.get(user_id)


# def role_required(role):
#     def wrapper(fn):
#         @wraps(fn)
#         @login_required
#         def decorated_view(*args, **kwargs):
#             if current_user.role != role:
#                 flash('You do not have permission to access this.')
#                 return jsonify("You do not have permission to access this.")
#             return fn(*args, **kwargs)
#
#         return decorated_view
#
#     return wrapper


def permission_required(required_permissions):
    def wrapper(fn):
        @login_required
        def decorated_view(*args, **kwargs):
            if not any(current_user.has_permission(permission) for permission in required_permissions):
                return jsonify({'message': 'Access denied'}), 403
            return fn(*args, **kwargs)

        decorated_view.__name__ = fn.__name__
        return decorated_view

    return wrapper


@app.route('/logout')
def logout():
    logout_user()
    return jsonify({"msg": "ok"})


@app.route('/')
def index():
    return render_template("register.html")


@app.route('/add')
# @role_required('admin')
def add():
    return render_template("add.html")


@app.route('/tologin')
def tologin():
    return render_template("login.html")


@app.route('/toregister')
def toregister():
    return render_template("register.html")


@app.route('/toindex')
# @login_required
@permission_required(['admin', 'root'])
def toindex():
    url = request.args.get("url")
    # level = request.args.get("level")
    print(url)
    # print(level)
    if url == 'toequipment':
        return render_template("index.html", eq=get_equipment())
    elif url == 'toservice':
        return render_template("index.html", s=get_service())
    elif url == 'touser':
        return render_template("index.html", u=selectUser())
    elif url == 'torecord':
        return render_template("index.html", r=get_record())
    elif url == 'toequipmentfault':
        return render_template("index.html", eq_f=selectEquipmentFault())
    # elif level == '1' and index == '2':
    #     return render_template("index.html", eq=get_equipment())
    # elif level == '1' and index == '4':
    #     return render_template("index.html", r=get_record())
    # elif level == '2' and index == '2':
    #     return render_template("index.html", s=get_service())
    # elif level == '2' and index == '5':
    #     return render_template("index.html", eq_f=selectEquipmentFault())
    # elif level == '3' and index == '1':
    #     return render_template("index.html", eq=get_equipment())
    # elif level == '3' and index == '2':
    #     return render_template("index.html", s=get_service())
    # elif level == '3' and index == '5':
    #     return render_template("index.html", eq_f=selectEquipmentFault())
    else:
        return render_template("index.html")

    # if index == '1':
    #     return render_template("index.html", eq=get_equipment())
    # elif index == '2':
    #     return render_template("index.html", s=get_service())
    # elif index == '3':
    #     return render_template("index.html", u=selectUser())
    # elif index == '4':
    #     return render_template("index.html", r=get_record())
    # elif index == '5':
    #     return render_template("index.html", eq_f=selectEquipmentFault())


@app.route('/home')
def tohome():
    return render_template("home.html")


@app.route('/register', methods=['POST'])
def register():
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        print(username)
        print(password)

        user = User.query.filter_by(user_name=username).first()
        if user:
            return jsonify("用户名已存在，无法注册")
        else:
            random_uuid = uuid.uuid4()
            new_user = User(id=random_uuid, user_name=username, password=password, role='user')
            print(new_user)
        try:
            db.session.add(new_user)
            db.session.commit()
            flash('Your account has been created! You are now able to log in', 'success')
            return jsonify(
                {"msg": "ok"})
        except:
            flash('Username already exists. Please try a different one.', 'danger')
            return jsonify({"msg": "error"})


@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        user = User.query.filter_by(user_name=username).first()
        if user and user.password == password:

            login_user(user)
            # 这里你可以设置会话变量来保持用户登录状态
            session['user_name'] = user.user_name
            # return redirect(url_for('index'))
            if user.role == 'user' or user.role == 'maintainer':
                rurl = "/home"
            else:
                rurl = "/toindex?url=touser&page=1&per_page=10"
            return jsonify(
                {"msg": "ok",
                 "username": user.user_name,
                 "role": user.role,
                 "rurl": rurl
                 })  # 假设你有一个 profile 路由
        else:
            flash('Login Unsuccessful. Please check username and password', 'danger')
            return jsonify(
                {"msg": "error"})
